import React, {useEffect} from 'react';
import {
    Alert, BackHandler,
    Dimensions,
    Image, Keyboard,
    SafeAreaView,
    TextInput,
    ToastAndroid,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View
} from "react-native";
import { StyleSheet } from 'react-native';
import {
    Button,
    Card,
    Divider,
    Icon,
    Input,
    Layout, List,
    Tab,
    TabView,
    Text,
    TopNavigation,
    TopNavigationAction
} from '@ui-kitten/components';
import SorageManager from "../Compoments/SorageManager";
import nativeToastAndroid from "react-native/Libraries/Components/ToastAndroid/NativeToastAndroid";

import AsyncStorage from "@react-native-async-storage/async-storage";

const data = new Array(8).fill({
    title: 'Item',
});


/**
 * 活项领取
 * @param navigation
 * @returns {JSX.Element}
 * @constructor
 */
export const ReceiveLiveItemsScreen = ({ navigation }) => {

    const [livingItemList, setLivingItemList] = React.useState([]);

    const [livingDoneReceive, setLivingDoneReceive] = React.useState([]);


    //------------------------fatchAPI-----------------------------------//

    /**
     * 获取选择活项内容
     * @param jrd
     * @param rkid
     */
    const  livingItemChoose= (jrd,rkid)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };



        const  url = "http://htjoa.nrnet.cn/dc14/jwmis/LivingItem/choose?jrd="+jrd+"&rkid="+rkid;
        console.log(url)
        fetch(url, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取选择活项数据")
                setLivingItemList(result)
            })
            .catch(error => console.log('error', error));

    }


    /**
     * 获取以领活项
     * @param jrd
     * @param wxr 维修人 -> userID
     * @param ch
     */
    const livingItemDoneReceive =(jrd,wxr,ch) =>{

        const  requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch("http://htjoa.nrnet.cn/dc14/jwmis/LivingItem/doneReceive?jrd="+jrd+"&wxr="+wxr+"&ch="+ch, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"获取已领活项")
                setLivingDoneReceive(result)

            })
            .catch(error => console.log('error', error));
    }

    /**
     * 选择活项中的添加功能
     * @param wxr
     * @param id
     */
    const livingItemUpdate= (id) =>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        SorageManager.get('userInf').then(r => {
        const url = "http://htjoa.nrnet.cn/dc14/jwmis/acceptancerepair/livingItemUpdate?wxr="+r["userid"]+"&id="+id
            console.log(url)

        fetch(url, requestOptions)
            .then(response => response.text())
            .then(async result => {
                console.log(result, "添加结果")

                if (result === "success") {
                    showToast("添加成功")
                    const s = await AsyncStorage.getItem("search1")
                    if (s === undefined || s  === null) {
                        livingItemChoose(r["belongduan"], '')
                    } else {
                        livingItemChoose(r["belongduan"], s)
                    }


                } else {
                    showToast("添加失败，请刷新重试")
                }
            })
            .catch(error => console.log('error', error));
        })
    }


    /**
     * 选择活项中的取消功能
     * @param wxr
     * @param id
     */
    const cancelItem= (id) =>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        SorageManager.get('userInf').then(r => {

            fetch("http://htjoa.nrnet.cn/dc14/jwmis/acceptancerepair/cancelItem?id="+id, requestOptions)
                .then(response => response.text())
                .then(result => {
                    console.log(result,"添加结果")

                    if (result === "success"){
                        showToast("取消成功")
                        livingItemDoneReceive(r["belongduan"],r["userid"],"")
                    }else {
                        showToast("取消失败 该活项已操作 ")
                    }
                })
                .catch(error => console.log('error', error));
        })
    }


    useEffect(()=>{

        SorageManager.set("search1",'')
        Keyboard.addListener("keyboardDidHide", _keyboardDidHide);
        SorageManager.get('userInf').then(async r => {
            console.log(r, "userINF")
            const s = await AsyncStorage.getItem("search1")
            if (s === undefined  || s  === null) {
                livingItemChoose(r["belongduan"], '')
                livingItemDoneReceive(r["belongduan"], r["userid"], "")
            } else {
                livingItemChoose(r["belongduan"], s)
                livingItemDoneReceive(r["belongduan"], r["userid"], s)
            }

        } )

        // cleanup function
        return () => {
            Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
        };

    },[])



    const _keyboardDidHide = () => {
        console.log(value)
        SorageManager.get('userInf').then(async r => {
            const s = await AsyncStorage.getItem("search1")
            if (s === undefined || s === null) {
                livingItemChoose(r["belongduan"], '')
                livingItemDoneReceive(r["belongduan"], r["userid"], "")
            } else {
                livingItemChoose(r["belongduan"], s)
                livingItemDoneReceive(r["belongduan"], r["userid"], s)
            }
        })

    };


    const showToast = (message) => {
        ToastAndroid.show(message, ToastAndroid.SHORT);
    };
    const navigateAddTicketCollection = () => {
        navigation.navigate('AddTicketCollection');
    };



    const renderItemHeader = (headerProps, info) => (
        <View {...headerProps} style={{alignItems: 'center',margin:10}}>
            <Text category='h6' >
                车型： {info.item.firstname}        车号： {info.item.ch}
            </Text>
        </View>
    );

    const renderItemFooter = (footerProps, info) => (
        <Button onPress={( )=> livingItemUpdate(info.item.id)} >
            添加
        </Button>
    );

    const renderItem = (info) => (
        <Card
            style={styles.item}
            status='basic'
            header={headerProps => renderItemHeader(headerProps, info)}
            footer={footerProps => renderItemFooter(footerProps,info)}>
            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        提票人: {info.item.wxtqrhz}
                    </Text>
                </Layout>

            </Layout>

            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                      故障名称：
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        {info.item.gzxx}
                    </Text>
                </Layout>

            </Layout>


        </Card>
    );


    const accept = (info) => (
        <Card
            style={styles.item}
            status='success'
            header={headerProps => renderItemHeader(headerProps, info)}
            footer={footerProps => renderacceptFooter(footerProps, info)}>

            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        提票人:{info.item.wxtqrhz}
                    </Text>
                </Layout>
            </Layout>



            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        领活时间:{info.item.wxlqrq}
                    </Text>
                </Layout>
            </Layout>

            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                    故障名称：
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        {info.item.gzxx}
                    </Text>
                </Layout>

            </Layout>


        </Card>
    );

    // const deleteButton = (footerProps,info)=>{
    //     cancelItem(info.item.info)
    // }

    const renderacceptFooter = (footerProps,info) => (
        <Button appearance='outline' status='warning' onPress={()=>cancelItem(info.item.id)}>
            取消
        </Button>
    );


    // const BackIcon = (props) => (
    //     <Icon {...props} name='arrow-back' />
    // );
    // const navigateBack = () => {
    //     navigation.goBack();
    // };
    // const BackAction = () => (
    //     <TopNavigationAction icon={BackIcon} onPress={navigateBack}/>
    // );

    const BackIcon = (props) => (
        <Icon {...props} name='arrow-back'/>
    );

    const navigateMenu = () => {
        navigation.navigate('Menu');
    };

    const BackAction = () => (
        <TopNavigationAction icon={BackIcon} onPress={navigateMenu}/>
    );

    const [selectedIndex, setSelectedIndex] = React.useState(0);
    const [value, setValue] = React.useState('');
    return (
        <View style={{ flex: 1 }}>
            <TopNavigation

                accessoryLeft={BackAction}

                title='领取活项' alignment='center' />
            <Divider/>
            <TabView
                selectedIndex={selectedIndex}
                onSelect={(index) => {
                    setSelectedIndex(index)
                    SorageManager.get('userInf').then(async r => {
                        console.log(r, "userINF")
                        const s = await AsyncStorage.getItem("search1")
                        if (s === undefined  || s === null) {
                            livingItemChoose(r["belongduan"], '')
                            livingItemDoneReceive(r["belongduan"], r["userid"], "")
                        } else {
                            livingItemChoose(r["belongduan"], s)
                            livingItemDoneReceive(r["belongduan"], r["userid"], s)
                        }
                    })

                }}>
                <Tab title='选择活项'>
                    <Layout style={styles.tabContainer}>


                        <View style={{flexDirection:'row',justifyContent: 'center',marginTop:10,marginBottom:10}}>

                            <Input
                                style={{width:Dimensions.get('window').width-20}}
                                value={value}
                                placeholder='机车号模糊查找'
                                accessoryRight={(<Icon
                                    onPress={()=>{
                                        SorageManager.get('userInf').then(r =>{
                                            console.log(r,"userINF")
                                            livingItemChoose(r["belongduan"],'')
                                            livingItemDoneReceive(r["belongduan"],r["userid"],"")
                                            SorageManager.set("search1",'')
                                            ToastAndroid.show("取消查询", ToastAndroid.SHORT);
                                            setValue('')
                                        } )



                                    }}
                                    style={styles.icon}
                                    fill='#8F9BB3'
                                    name='close-outline'
                                />)}
                                // secureTextEntry={secureTextEntry}
                                onChangeText={async nextValue => {
                                        setValue(nextValue);
                                        console.log(nextValue,"存储值")
                                        console.log(typeof  nextValue)
                                        //  SorageManager.set("Search1",nextValue)
                                        await AsyncStorage.setItem("search1", nextValue)

                                    }

                                }
                            />

                            {/*<Input*/}
                            {/*       placeholder='机车号'*/}
                            {/*       value={value}*/}
                            {/*       onChangeText={nextValue => setValue(nextValue)}>*/}
                            {/*</Input>*/}

                        </View>

                        <Divider/>
                        <List
                            style={styles.container}
                            contentContainerStyle={styles.contentContainer}
                            data={livingItemList}
                            renderItem={renderItem}
                        />

                    </Layout>
                </Tab>

                <Tab title='已领取活项'>
                    <Layout style={styles.tabContainer}>
                        <List
                            style={styles.container}
                            contentContainerStyle={styles.contentContainer}
                            data={livingDoneReceive}
                            renderItem={accept}
                        />

                    </Layout>
                </Tab>
            </TabView>

        </View>
    );
};

const styles = StyleSheet.create({
    container: {

    },
    contentContainer: {
        paddingHorizontal: 15,
        // paddingVertical: 4,
    },
    item: {
        marginTop:15,
        // marginVertical: 4,

    },

    tabContainer: {
        height: Dimensions.get('window').height-118,
    },

    textContainer:{
        flexDirection:'row',
        flexWrap:'wrap',
        justifyContent:"space-evenly",
        alignItems:"center",
        marginBottom:10

    },
    textItem:{
        justifyContent:'center',
        alignItems:'center',

    }
});